<?php
    //
    //  Created by Chagan Anton on 29.07.12.
    //  Copyright Chagan Anton 2012. All rights reserved.
    //
class SiteController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
		// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
		),
		// page action renders "static" pages stored under 'protected/views/site/pages'
		// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
		),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		$api = new xtifyApi("notif_config");
		$api->nc->apiKey="c49e69ac-6549-41d5-82ef-f88fee4bc6dc";
		$api->listNC();
		//var_dump($api->response); 
		$this->render('index',array('model'=>$api));
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
			echo $error['message'];
			else
			$this->render('error', $error);
		}
	}

	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		$model=new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				$headers="From: {$model->email}\r\nReply-To: {$model->email}";
				mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));
//                $this->render('contact_fox');
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
			$this->redirect(Yii::app()->user->returnUrl);
		}
		// display the login form
		$this->render('login',array('model'=>$model));
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
	
	public function actionMap()
	{
		$users="http://locations.emission-framework.com/?LocationWebService/dumpRuntimes";
		$coordinates="http://locations.emission-framework.com/?LocationWebService/dumpContexts";
		//$coordinates="dump.json";
		
		//$list_users=
		
		//var_dump($ctx);
		//echo $ctx [0]->context;
		
		
		
		if(isset($_GET['id']))
		{//echo $_GET['id'];
		//echo $ctx [array_search($_GET['id'],$ctx)]->id; 
		$n=$_GET['id'];
		$response=array();
		if ($n=="") $result=file_get_contents($coordinates);
		else
		//echo $coordinates."&userIdentifier=".$n;
		$result=file_get_contents($coordinates."&userIdentifier=".$n);
		$result= trim($result,"\"");
		$result= stripslashes ($result);
		$result= str_replace ("\"_object\" : undefined","\"_object\" : \"undefined\"",$result);
		//echo $result;
		$ctx=json_decode($result); 
		/* if(isset($_GET['coords_id']))
		{
		echo "coords_id=".$_GET['coords_id'];
		echo "id=".$_GET['id']; */
		for ($i=0; $i < count($ctx);  $i++){
		//if ($ctx[$i]->id == $_GET['coords_id']) {echo $ctx[$i]->context;}
		//$temp ["lat"]=json_decode(
		$temp=json_decode($ctx[$i]->context);
		//echo $temp[0][0];
		//);
		if ($temp=="") continue;
		$response[]=$temp[0];
		//$response[$i]["lng"]=json_decode($ctx[$i]->context)[1];
		}
		echo json_encode($response);
		 Yii::app()->end();
  		/*}
		$this->renderPartial('map_show',array(
			'model'=>$ctx,
			'id'=>$_GET['id'],
			),false, true); */
		//echo json_encode($ctx);
		}
		else 
		{
		$list_users=file_get_contents($users);
		$list_users= trim($list_users,"\"");
		$list_users= stripslashes ($list_users);
		$list_users= str_replace ("\"_object\" : undefined","\"_object\" : \"undefined\"",$list_users);
		$list_users= json_decode($list_users);
		/* //$users=array();
		foreach ($list_users as $u)
		//if (!is_array($u->user_id)) 
		{//$users ['name']=$u->name;
		$tmp=array('id'=>$u->user_id,'name'=>$u->name);
		$users[] = $tmp;} */
		$this->render('map',array(
				'users'=>$list_users,
			));  
		}
		
		 /*  $this->render('map',array(
			'model'=>$ctx,
			'users'=>$list_users,
			));   */
			//var_dump($ctx); 
	}
	
	public function actionGoogleGeocode() {
	
	$this->render('geocode');
	}
	
	public function actionInstall() {
	echo 'install action! /n';
		// получаем запись с ID=10
	$msg=Msg::model()->findByPk(1);
	// Получаем автора записи. Здесь будет выполнен реляционный запрос.
	//$author=$msg->text;
	echo $msg->andr->notification_link_label;
	//echo $msg->content;
	//echo $author;
	}
}